<template>
  <div class="calendar-view">
    <div class="calendar-header">
      <button @click="prevMonth" class="nav-btn">&lt;</button>
      <h3 class="calendar-title">{{ currentMonthYear }}</h3>
      <button @click="nextMonth" class="nav-btn">&gt;</button>
    </div>
    
    <div class="calendar-grid">
      <div class="calendar-weekdays">
        <div v-for="day in weekdays" :key="day" class="weekday">{{ day }}</div>
      </div>
      
      <div class="calendar-days">
        <div 
          v-for="day in calendarDays" 
          :key="day.date"
          :class="['calendar-day', { 
            'current-month': day.isCurrentMonth,
            'today': day.isToday,
            'has-todos': day.todos.length > 0
          }]"
          @click="selectDate(day.date)"
        >
          <div class="day-number">{{ day.day }}</div>
          <div class="day-todos">
            <div 
              v-for="todo in day.todos.slice(0, 3)" 
              :key="todo.id"
              class="todo-dot"
              :title="todo.title"
              @click.stop="$emit('todo-clicked', todo)"
            ></div>
            <div v-if="day.todos.length > 3" class="more-todos">
              +{{ day.todos.length - 3 }}
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 选中日期的任务列表 -->
    <div v-if="selectedDate" class="date-todos">
      <h4>{{ selectedDateFormatted }} 的任务</h4>
      <div v-if="todosForSelectedDate.length === 0" class="no-todos">
        这一天没有任务
      </div>
      <ul v-else>
        <li 
          v-for="todo in todosForSelectedDate" 
          :key="todo.id"
          :class="['todo-item', { completed: todo.completed }]"
          @click="$emit('todo-clicked', todo)"
        >
          <span class="todo-title">{{ todo.title }}</span>
          <span class="todo-time" v-if="todo.dueDate">
            {{ formatTodoTime(todo.dueDate) }}
          </span>
          <span class="todo-priority" :class="todo.priority">
            {{ getPriorityText(todo.priority) }}
          </span>
        </li>
      </ul>
    </div>
  </div>
</template>

<script>
export default {
  name: 'CalendarView',
  props: {
    todos: {
      type: Array,
      default: () => []
    }
  },
  data() {
    return {
      currentDate: new Date(),
      selectedDate: null,
      weekdays: ['日', '一', '二', '三', '四', '五', '六']
    }
  },
  computed: {
    currentMonthYear() {
      return this.currentDate.toLocaleDateString('zh-CN', { 
        year: 'numeric', 
        month: 'long' 
      });
    },
    calendarDays() {
      const year = this.currentDate.getFullYear();
      const month = this.currentDate.getMonth();
      
      // 本月第一天
      const firstDay = new Date(year, month, 1);
      // 本月最后一天
      const lastDay = new Date(year, month + 1, 0);
      // 本月天数
      const daysInMonth = lastDay.getDate();
      
      // 上个月最后一天
      const prevMonthLastDay = new Date(year, month, 0).getDate();
      
      // 本月第一天是星期几 (0-6, 0=Sunday)
      const firstDayOfWeek = firstDay.getDay();
      
      const days = [];
      
      // 添加上个月的日期
      for (let i = firstDayOfWeek - 1; i >= 0; i--) {
        const day = prevMonthLastDay - i;
        const date = new Date(year, month - 1, day);
        days.push({
          date: this.formatDateForComparison(date),
          day,
          isCurrentMonth: false,
          isToday: this.isToday(date),
          todos: this.getTodosForDate(date)
        });
      }
      
      // 添加本月的日期
      for (let day = 1; day <= daysInMonth; day++) {
        const date = new Date(year, month, day);
        days.push({
          date: this.formatDateForComparison(date),
          day,
          isCurrentMonth: true,
          isToday: this.isToday(date),
          todos: this.getTodosForDate(date)
        });
      }
      
      // 添加下个月的日期，使总天数为42天（6周）
      const remainingDays = 42 - days.length;
      for (let day = 1; day <= remainingDays; day++) {
        const date = new Date(year, month + 1, day);
        days.push({
          date: this.formatDateForComparison(date),
          day,
          isCurrentMonth: false,
          isToday: this.isToday(date),
          todos: this.getTodosForDate(date)
        });
      }
      
      return days;
    },
    selectedDateFormatted() {
      if (!this.selectedDate) return '';
      const date = new Date(this.selectedDate);
      return date.toLocaleDateString('zh-CN', { 
        month: 'long', 
        day: 'numeric',
        weekday: 'long'
      });
    },
    todosForSelectedDate() {
      if (!this.selectedDate) return [];
      return this.getTodosForDate(new Date(this.selectedDate));
    }
  },
  methods: {
    // 格式化日期用于比较，使用本地时间而非UTC时间
    formatDateForComparison(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },
    
    prevMonth() {
      this.currentDate = new Date(this.currentDate.getFullYear(), this.currentDate.getMonth() - 1, 1);
    },
    nextMonth() {
      this.currentDate = new Date(this.currentDate.getFullYear(), this.currentDate.getMonth() + 1, 1);
    },
    isToday(date) {
      const today = new Date();
      return this.formatDateForComparison(date) === this.formatDateForComparison(today);
    },
    getTodosForDate(date) {
      return this.todos.filter(todo => {
        if (!todo.dueDate) return false;
        const todoDate = new Date(todo.dueDate);
        return this.formatDateForComparison(todoDate) === this.formatDateForComparison(date);
      });
    },
    selectDate(date) {
      this.selectedDate = date;
    },
    formatTodoTime(dueDate) {
      if (!dueDate) return '';
      const date = new Date(dueDate);
      return date.toLocaleTimeString('zh-CN', { 
        hour: '2-digit', 
        minute: '2-digit' 
      });
    },
    getPriorityText(priority) {
      const priorityMap = {
        'high': '高',
        'medium': '中',
        'low': '低'
      };
      return priorityMap[priority] || priority;
    }
  }
}
</script>

<style scoped>
.calendar-view {
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 5px rgba(0,0,0,0.1);
  padding: 20px;
}

.calendar-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.calendar-title {
  margin: 0;
  color: #34495e;
  font-size: 1.5rem;
}

.nav-btn {
  background-color: #3498db;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px 15px;
  cursor: pointer;
  font-size: 1rem;
  transition: background-color 0.3s;
}

.nav-btn:hover {
  background-color: #2980b9;
}

.calendar-grid {
  display: grid;
  grid-template-rows: auto 1fr;
}

.calendar-weekdays {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  text-align: center;
  font-weight: bold;
  color: #7f8c8d;
  margin-bottom: 10px;
}

.calendar-days {
  display: grid;
  grid-template-columns: repeat(7, 1fr);
  gap: 1px;
  background-color: #eee;
}

.calendar-day {
  background-color: white;
  min-height: 80px;
  padding: 5px;
  cursor: pointer;
  transition: background-color 0.2s;
  position: relative;
}

.calendar-day:hover {
  background-color: #f8f9fa;
}

.calendar-day:not(.current-month) {
  background-color: #f8f9fa;
  color: #bbb;
}

.calendar-day.today {
  background-color: #e3f2fd;
  border: 2px solid #2196f3;
}

.calendar-day.today:not(.current-month) {
  background-color: #f0f8ff;
}

.day-number {
  font-weight: bold;
  margin-bottom: 5px;
}

.day-todos {
  display: flex;
  flex-wrap: wrap;
  gap: 2px;
}

.todo-dot {
  width: 8px;
  height: 8px;
  border-radius: 50%;
  background-color: #3498db;
  cursor: pointer;
}

.todo-dot:hover {
  transform: scale(1.2);
}

.more-todos {
  font-size: 0.8rem;
  color: #7f8c8d;
}

.date-todos {
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #eee;
}

.date-todos h4 {
  color: #34495e;
  margin-bottom: 15px;
}

.no-todos {
  text-align: center;
  color: #95a5a6;
  font-style: italic;
  padding: 20px;
}

.todo-item {
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  cursor: pointer;
  transition: box-shadow 0.2s;
}

.todo-item:hover {
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.todo-item.completed .todo-title {
  text-decoration: line-through;
  color: #95a5a6;
}

.todo-title {
  flex: 1;
  font-weight: 500;
}

.todo-time {
  margin: 0 10px;
  color: #7f8c8d;
  font-size: 0.9rem;
}

.todo-priority {
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 0.8rem;
  font-weight: bold;
}

.todo-priority.high {
  background-color: #ffebee;
  color: #c62828;
}

.todo-priority.medium {
  background-color: #fff8e1;
  color: #f57f17;
}

.todo-priority.low {
  background-color: #e8f5e9;
  color: #2e7d32;
}

@media (max-width: 768px) {
  .calendar-days {
    gap: 1px;
  }
  
  .calendar-day {
    min-height: 60px;
    padding: 3px;
  }
  
  .day-number {
    font-size: 0.9rem;
  }
  
  .todo-dot {
    width: 6px;
    height: 6px;
  }
}
/* 夜间模式样式 */
.dark-mode .calendar-view {
  background-color: #2d2d2d;
  color: #e0e0e0;
}

.dark-mode .calendar-title {
  color: #e0e0e0;
}

.dark-mode .nav-btn {
  background-color: #1976d2;
  color: white;
}

.dark-mode .nav-btn:hover {
  background-color: #1565c0;
}

.dark-mode .calendar-days {
  background-color: #424242;
}

.dark-mode .calendar-day {
  background-color: #333;
}

.dark-mode .calendar-day:not(.current-month) {
  background-color: #2d2d2d;
  color: #777;
}

.dark-mode .calendar-day.today {
  background-color: #1565c0;
  border-color: #1976d2;
}

.dark-mode .calendar-day.today:not(.current-month) {
  background-color: #0d47a1;
}

.dark-mode .todo-dot {
  background-color: #64b5f6;
}

.dark-mode .date-todos {
  border-color: #555;
}

.dark-mode .date-todos h4 {
  color: #e0e0e0;
}

.dark-mode .no-todos {
  color: #aaa;
}

.dark-mode .todo-item {
  background-color: #424242;
  border-color: #555;
}

.dark-mode .todo-item:hover {
  box-shadow: 0 2px 8px rgba(0,0,0,0.3);
}

.dark-mode .todo-item.completed .todo-title {
  color: #aaa;
}

.dark-mode .todo-time {
  color: #aaa;
}

.dark-mode .todo-priority.high {
  background-color: #c62828;
  color: white;
}

.dark-mode .todo-priority.medium {
  background-color: #f57f17;
  color: white;
}

.dark-mode .todo-priority.low {
  background-color: #2e7d32;
  color: white;
}

</style>